import { ref } from 'vue';
import { getGlobalMap } from '@/components/GlobalMap';
import { addPointDataLayer, addLineStringLayer, addPolygonLayer } from 'gmap-ol';
import { RRIcon, PPIcon } from '@/setting/imageEnum';
import { PPIcon ,PPIcon0, PPIcon5, PPIcon10, PPIcon20, PPIcon50, PPIcon100 } from '@/setting/imageEnum';
import { getTownBoundaryJson, getVillageJson, getWaterLineStringJson, getWaterPolygonJson } from '@/api/mapServices/geojson';
import dayjs from "dayjs";

const globalMap = ref<any>(null);

// 添加需要的地图数据
export const addMapData = async (rainData, RR_Data) => {
  globalMap.value = getGlobalMap();
  addReservoirData(RR_Data); // 水库站
  addRainfallData(rainData); // 雨量站

  addTownBoundaryJson();  // 镇边界
  addVillageJson();  // 行政区村
  addWaterLineStringJson();  // 水系线
  addWaterPolygonJson();  // 水系面
}

// 水库站
const addReservoirData = async (RR_Data) => {
  const RRData = RR_Data.map(item => {
    return {...item, sttp: 'RR'};
  });
  const pointOptions = {
    layerName: 'RR-PointLayer',
    icon: RRIcon,
    zIndex: 100,
    visible: true,
    textFieldName: '', // stnm
    styles: {
      image: {
        scale: 0.8,
      },
      text: {
        fill: {
          color: 'rgba(76, 82, 70, 0.9)',
        },
        stroke: {
          width: 2,
          color: 'rgba(255, 255, 255, 0.8)',
        },
        font: '11px sans-serif',
      },
    },
  };
  addPointDataLayer(globalMap.value, RRData, pointOptions);
}

// 雨量站
// const addRainfallData = (PP_Data) => {
//   const PPData = PP_Data.map(item => {
//     return {...item, sttp: 'PP'};
//   });
//   const pointOptions = {
//     layerName: 'PP-PointLayer',
//     icon: PPIcon,
//     zIndex: 100,
//     visible: true,
//     textFieldName: '', // stnm
//     styles: {
//       image: {
//         scale: 0.85,
//       },
//       text: {
//         fill: {
//           color: 'rgba(76, 82, 70, 0.9)',
//         },
//         stroke: {
//           width: 2,
//           color: 'rgba(255, 255, 255, 0.8)',
//         },
//         font: '11px sans-serif',
//       },
//     },
//   };
//   addPointDataLayer(globalMap.value, PPData, pointOptions);
// }


// 雨量站 - 按 ph 值分成 6 个级别，分别渲染不同的图标
const addRainfallData = (PP_Data) => {
  // 定义 6 个不同级别的图标
  const levelIcons = [
    PPIcon0, // 第 1 级（ph ≤ 10）
    PPIcon, // 第 2 级（10 < ph ≤ 20）
    PPIcon5, // 第 3 级（20 < ph ≤ 30）
    PPIcon10, // 第 4 级（30 < ph ≤ 40）
    PPIcon20, // 第 5 级（40 < ph ≤ 50）
    PPIcon50 , // 第 6 级（ph > 50）,
    PPIcon100
  ];

  // 按 ph 值分成 6 个级别
  const now = dayjs(); // 当前时间

// 1. 先筛选出满足时间条件的数据（Level 1）
  let timeFilteredData = [];
// 2. 剩下的数据按 ph 值分组（Level 2 - Level 7）
  let  remainingData =[];
  for(let i=0;i<PP_Data.length;i++){
    if(dayjs(PP_Data[i].tm).add(24, "hour") >= now){
      remainingData.push(PP_Data[i]);
    }else{
      timeFilteredData.push(PP_Data[i]);
    }
  }
  //console.log('remainingDataremainingDataremainingData',remainingData)
  const phLevelData = [
    remainingData.filter(item => item.ph >= 0 && item.ph <= 58.1),     // Level 2
    remainingData.filter(item => item.ph > 58.1 && item.ph <= 70.6),  // Level 3
    remainingData.filter(item => item.ph > 70.6 && item.ph <= 82.6),  // Level 4
    remainingData.filter(item => item.ph > 82.6 && item.ph <= 98),    // Level 5
    remainingData.filter(item => item.ph > 98 && item.ph <= 109.4),   // Level 6
    remainingData.filter(item => item.ph > 109.4),                    // Level 7
  ];

// 合并所有层级（Level 1 + Level 2-7）
  const levelData = [timeFilteredData, ...phLevelData];

  // 遍历 6 个级别，分别渲染不同的图标
  levelData.forEach((data, index) => {
    if (data.length === 0) return; // 如果该级别没有数据，跳过

    const PPData = data.map(item => ({
      ...item,
      sttp: 'PP'
    }));

    //console.log('PPDataPPDataPPData---index',index+"----------------")
    //console.log('PPDataPPDataPPData---index',PPData)
    const pointOptions = {
      layerName: `PP-PointLayer-Level${index + 1}`, // 不同级别用不同图层名
      icon: levelIcons[index], // 使用对应的图标
      zIndex: 100 + index, // 层级递增，避免覆盖
      visible: true,
      textFieldName: '', // stnm
      styles: {
        image: {
          scale: 0.85,
        },
        text: {
          fill: {
            color: 'rgba(76, 82, 70, 0.9)',
          },
          stroke: {
            width: 2,
            color: 'rgba(255, 255, 255, 0.8)',
          },
          font: '11px sans-serif',
        },
      },
    };

    addPointDataLayer(globalMap.value, PPData, pointOptions);
  });
};

// 镇边界
const addTownBoundaryJson = async () => {
  const townBoundaryJson = await getTownBoundaryJson();
  // lineString 的 Options
  const lineStringOptions = {
    layerName: 'townBoundary-LineStringLayer',
    zIndex: 10,
    textFieldName: 'XZQMC',
    visible: true,
    styles: {
      stroke: {
        width: 2,
        color: 'rgba(143, 124, 237, 0.8)',
        lineDash: [6, 6, 6, 6],
      },
      text: {
        fill: {
          color: 'rgba(143, 124, 237, 0.9)',
        },
        stroke: {
          width: 3,
          color: 'rgba(255, 255, 255, 0.8)',
        },
        font: 'italic 13px bold sans-serif',
      },
    },
  };
  addPolygonLayer(globalMap.value, townBoundaryJson, lineStringOptions);
}

// 行政区村
const addVillageJson = async () => {
  const villageJson = await getVillageJson();
  const polygonOptions = {
    layerName: 'village-PolygonLayer',
    zIndex: 10,
    textFieldName: 'XZQMC',
    visible: true,
    styles: {
      stroke: {
        width: 1,
        color: 'rgba(180, 171, 163, 0.8)',
        lineDash: [8, 4, 8, 4],
      },
      text: {
        fill: {
          color: 'rgba(127, 106, 0, 0.7)',
        },
        stroke: {
          width: 2,
          color: 'rgba(255, 255, 255, 0.7)',
        },
        font: 'italic 11px bold sans-serif',
      },
    }
  };
  addPolygonLayer(globalMap.value, villageJson, polygonOptions);
}

// 水系线
const addWaterLineStringJson = async () => {
  const waterLineStringJson = await getWaterLineStringJson();
  const lineStringOptions = {
    layerName: 'water-LineStringLayer',
    zIndex: 20,
    textFieldName: 'name',
    styles: {
      stroke: {
        width: 3,
        color: 'rgba(152, 181, 221, 1)',
      },
      text: {
        fill: {
          color: 'rgba(50, 120, 255, 0.8)',
        },
        stroke: {
          width: 2,
          color: 'rgba(255, 255, 255, 0.7)',
        },
        font: 'italic 11px bold sans-serif',
      },
    },
  };
  addLineStringLayer(globalMap.value, waterLineStringJson, lineStringOptions);
}

// 水系面
const addWaterPolygonJson = async () => {
  const waterPolygonJson = await getWaterPolygonJson();
  const polygonOptions = {
    layerName: 'water-PolygonLayer',
    zIndex: 10,
    textFieldName: 'name',
    styles: {
      fill: {
        color: 'rgba(152, 181, 221, 1)',
      },
      stroke: {
        width: 2,
        color: 'rgba(152, 181, 221, 1)',
      },
      text: {
        fill: {
          color: 'rgba(50, 120, 255, 0.8)',
        },
        stroke: {
          width: 2,
          color: 'rgba(255, 255, 255, 0.8)',
        },
        font: 'italic bold 12px sans-serif',
      },
    }
  };
  addPolygonLayer(globalMap.value, waterPolygonJson, polygonOptions);
}
